<template>
  <div class="addEditActivity">
    <div class="acrivityTitle">
      <h2>{{ acBasicsReq.name }}</h2>
      <div>
        <Button style="margin-right: 5px" type="primary" @click="closeCurrent">关闭</Button>
        <Button style="margin-right: 5px" :disabled="statusLastFlag" type="primary" @click="saveCurrent">
          保存
        </Button>
        <Button style="margin-right: 5px" type="primary" :disabled="statusLastFlag" @click="releaseCurrent">
          预览/发布
        </Button>
      </div>
    </div>

    <div class="setBoth">
      <div class="bothLeft">
        <div class="viewClass">预览：（保存后，即可在下方预览活动样式）</div>
        <div class="yeTit">
          <span
            v-for="(item, index) in yeTit"
            :key="item.id"
            class="title"
            :class="{ active: num == index }"
            @click="onGetIdx(index)">
            {{ item.name }}
          </span>
        </div>
        <div class="yeCon" id="v2ex">
          <div class="yeCOnTel" v-if="num == 2">
            <span>{{ acBasicsReq.phone }}</span>
            <img src="@/assets/images/prize.png" />
          </div>
          <iframe
            v-if="(num == 0 || num == 1) && imgFlag"
            :src="iframeUrl"
            style="width: 100%; height: 100%"
            frameborder="0"
            id="myIframe"
            ref="myIframe"></iframe>
        </div>
      </div>
      <div class="setAll">
        <Tabs v-model="tabsBox" type="card" name="father">
          <TabPane label="基础设置" name="1" tab="father">
            <dt-info :label-width="150" ref="info1" :options="options" style="width: 100%"></dt-info>
          </TabPane>
          <TabPane label="奖项设置" name="2" tab="father">
            <Tabs v-model="tabsChoose" :animated="false" type="card" @on-click="onClickTab" name="son">
              <TabPane
                :label="`奖品${index + 1}`"
                :name="String(index)"
                v-for="(item, index) in acPrizeReqList"
                :key="`${index}-${Math.random()}`"
                tab="son">
                <dt-info
                  :label-width="150"
                  ref="info2"
                  :info="item"
                  :options="options2"
                  style="width: 100%"></dt-info>
              </TabPane>
              <div slot="extra">
                <Button @click="addPrize" type="primary" size="small" style="margin-right: 5px">
                  添加新奖品
                </Button>
                <Button @click="removePrize" size="small" type="primary">删除该奖品</Button>
              </div>
            </Tabs>
          </TabPane>
          <TabPane label="抽奖设置" name="3" tab="father">
            <dt-info :label-width="150" ref="info3" :options="options3" style="width: 100%"></dt-info>
          </TabPane>
          <TabPane label="参与条件" name="4" tab="father">
            <div style="max-width: 1000px">
              <dt-info :label-width="150" ref="info4" :options="options4" style="width: 100%"></dt-info>
              <div v-if="conditionsFlag">
                <Form
                  ref="formValidate"
                  :model="acParticipationTaskReqList"
                  :rules="ruleValidate"
                  :label-width="0">
                  <div v-for="(item, index) in acParticipationTaskReqList.conditions" :key="index">
                    <div class="conditionsCon">
                      <FormItem>
                        <Select
                          style="width: 100px"
                          v-model="item.locationOptions"
                          @on-change="qualifiedChange">
                          <Option value="1">限定范围</Option>
                          <Option value="2">限定地区</Option>
                        </Select>
                      </FormItem>

                      <div class="conditionsAddress" v-if="item.locationOptions == '1'">
                        <!-- <div class="conditionsAddress"> -->
                        <FormItem>
                          <Input
                            type="text"
                            v-model="item.signAddress"
                            disabled
                            placeholder="请设置地点"></Input>
                        </FormItem>
                        <FormItem
                          :prop="`conditions.${index}.scope`"
                          key="ruleValidate.scope"
                          :rules="ruleValidate.scope">
                          <Input type="text" v-model="item.scope" disabled placeholder="请设置范围">
                            <template #append>
                              <span>米</span>
                            </template>
                          </Input>
                        </FormItem>

                        <Button @click="mapClick(item, index)">去设置</Button>
                      </div>

                      <div class="conditionscity" v-if="item.locationOptions == '2'">
                        <FormItem
                          :prop="`conditions.${index}.provinceCode`"
                          key="ruleValidate.provinceCode"
                          :rules="ruleValidate.provinceCode">
                          <Select
                            v-model="item.provinceCode"
                            placeholder="请选择省"
                            label-in-value
                            @on-change="
                              (e) => {
                                return provinceChange(e, item, index)
                              }
                            ">
                            <Option
                              v-for="(provinceItem, pIndex) in provinceList"
                              :key="pIndex"
                              :value="provinceItem.key"
                              :label="provinceItem.value" />
                          </Select>
                        </FormItem>
                        <FormItem>
                          <Select
                            v-model="item.cityCode"
                            placeholder="请选择市"
                            label-in-value
                            @on-change="
                              (e) => {
                                return cityChange(e, item, index)
                              }
                            ">
                            <Option
                              v-for="(cityItem, cIndex) in item.cityList"
                              :key="cIndex"
                              :value="String(cityItem.cityCode)">
                              {{ cityItem.cityName }}
                            </Option>
                          </Select>
                        </FormItem>
                        <FormItem>
                          <Select
                            v-model="item.areaCode"
                            placeholder="请选择区"
                            label-in-value
                            @on-change="
                              (e) => {
                                return areaChange(e, item, index)
                              }
                            ">
                            <Option
                              v-for="(areaItem, aIndex) in item.areaList"
                              :key="aIndex"
                              :value="String(areaItem.cityCode)">
                              {{ areaItem.cityName }}
                            </Option>
                          </Select>
                        </FormItem>
                      </div>

                      <div>
                        <Button
                          @click="upRemove(item, index)"
                          type="text"
                          :disabled="acParticipationTaskReqList.conditions.length < 2">
                          <Icon type="md-remove" />
                        </Button>
                        <Button @click="upAdd(item)" type="text">
                          <Icon type="md-add" />
                        </Button>
                      </div>
                    </div>
                  </div>
                </Form>
              </div>
            </div>
          </TabPane>
          <TabPane label="助力条件" name="5" tab="father" style="position: relative">
            <span class="sp1" @click="helpClick">
              <Icon type="md-help-circle" size="30" />
            </span>
            <dt-info :label-width="200" ref="info5" :options="options5" style="width: 100%"></dt-info>
          </TabPane>
        </Tabs>
      </div>
    </div>
    <map-range ref="mapRange" @mapInfo="mapInfo"></map-range>
    <help-model ref="helpModel"></help-model>
    <release-model ref="releaseModel" @publishUpdata="publishUpdata"></release-model>
    <img :src="base64Image" width="750" height="500" id="scream" style="display: none" />
    <canvas id="myCanvas" width="750" height="300" style="border: 1px solid #c3c3c3; display: none"></canvas>
  </div>
</template>
<script>
  import editMgr from './opt/edit.js'
  import dtEditor from '@/components/dt/editor/index.vue'
  import mapRange from './components/mapRange.vue'
  import releaseModel from './components/releaseModel.vue'
  import helpModel from './components/helpModel.vue'
  import activityMgr from '@/biz/activity/activity'
  import cityMgr from '@/biz/option/city'
  import moment from 'moment'
  export default {
    components: { dtEditor, mapRange, helpModel, releaseModel },

    data() {
      return {
        promoteSn: null,
        provinceList: null,
        ruleValidate: {
          scope: [{ pattern: /^\d+$/, required: true, message: '请设置范围', trigger: 'change' }],
          provinceCode: [
            {
              pattern: /^\d+$/,
              required: true,
              message: '请选择省份',
              trigger: 'change'
            }
          ]
        },

        conditionsFlag: false,
        imgFlag: false,
        base64Image: '',
        statusLastFlag: false,
        iframeWin: null,
        acId: this.$route.query.acId,
        status: '',
        iframeUrl: '',
        num: '0',
        yeTit: [
          { id: 0, name: '封面页' },
          { id: 1, name: '活动页' },
          { id: 2, name: '中奖页' }
        ],
        prizeLocationAll: [], //已选的奖品位置
        options: null,
        options2: null,
        options3: null,
        options4: null,
        options41: null,
        options5: null,
        tabsChoose: '0',
        tabsBox: '1',
        // tab1基础设置
        acBasicsReq: {
          accessoryBOList1: [], //活动封面图
          cover: '',
          accessoryBOList2: [], //顶部样式
          topStyle: '',
          accessoryBOList3: [], //线上售楼处
          onlineSalesOffice: '',
          accessoryBOList4: [], //项目展示
          projectShow: '',
          titleTag: '', //页面标题
          activityTime: [],
          startDate: '',
          endDate: '',
          reason: null, //活动说明
          phone: null //联系方式
        },
        // tab2奖品设置
        acPrizeReqList: [], //奖品名称
        optLocation: this.$formatter.optLocation(),
        // tab3抽奖设置
        acLotteryReq: {},
        // tab4参与条件
        acParticipationTaskReqList: {
          phoneAuthorization: true,
          locationLimitation: false, //地点限定开启
          conditions: []
        },
        // tab5助力条件
        assist: {
          seeFlag: false,
          videoId: '',
          contentId: '',
          seeDuration: null,
          getRaffleNum: null,
          shareFlag: false,
          shareNum: null
        }
      }
    },
    methods: {
      provinceChange(val, item, index) {
        if (val && val.label) {
          item.provinceName = val.label
          item.cityCode = ''
          item.areaCode = ''
          cityMgr.getareaCodeList(3, val.value).then((res) => {
            res = res.filter((cityChild) => {
              return (
                cityChild.cityName != '省直辖县级行政区划' &&
                cityChild.cityName != '自治区直辖县级行政区划' &&
                cityChild.cityName != '县'
              )
            })
            this.$set(this.acParticipationTaskReqList.conditions[index], 'cityList', res)
          })
        }
        this.$set(this.acParticipationTaskReqList.conditions[index], 'areaList', [])
      },
      cityChange(val, item, index) {
        if (val && val.label) {
          item.cityName = val.label
          item.areaCode = ''
          cityMgr.getareaCodeList(4, val.value).then((res) => {
            res = res.filter((areaChild) => {
              return (
                areaChild.cityName.indexOf('周边') == '-1' &&
                areaChild.cityName != '市辖区' &&
                areaChild.cityName != '郑州高新技术产业开发区' &&
                areaChild.cityName != '高新园区' &&
                areaChild.cityName != '高新区'
              )
            })
            this.$set(this.acParticipationTaskReqList.conditions[index], 'areaList', res)
          })
        }
      },
      areaChange(val, item) {
        if (val && val.label) {
          item.areaName = val.label
        }
      },
      getProvinceList() {
        cityMgr.getareaCodeList().then((res) => {
          this.provinceList = res
        })
      },
      qualifiedChange(val) {},

      // 3.7
      publishUpdata() {
        this.getDetails()
      },
      createPromoteRecord() {
        let params = {
          buildingId: this.$dt.buildInfo().housesId,
          contentId: this.acId,
          contentType: 8,
          promoteMethodId: 5,
          sendPort: 4,
          sendOrgId: this.$dt.buildInfo().housesId,
          sendOrgLevel: 'BUILDING'
        }
        activityMgr.createPromoteRecord(params).then((res) => {
          console.log(res, 'sn')
          if (res) {
            this.promoteSn = res.promoteSn
          }
        })
      },
      getDetails() {
        let params = {
          acId: this.acId
        }
        activityMgr.selectBasics(params).then((res) => {
          console.log('这边拿到了什么数据', res)
          if (res.acBasicsResp.promoteSn) {
            this.promoteSn = res.acBasicsResp.promoteSn
          } else {
            this.createPromoteRecord()
          }

          if (res.acBasicsResp.status == 'END') {
            this.statusLastFlag = true
          } else if (res.acBasicsResp.status == 'PUBLISHED') {
            let endTime = moment(res.acBasicsResp.endDate, 'YYYY-MM-DD kk:mm:ss').format('x')
            let cuttentTime = moment().format('x')
            if (cuttentTime > endTime) {
              this.statusLastFlag = true
            } else {
              this.statusLastFlag = false
            }
          }
          this.acBasicsReq.status = res.acBasicsResp.status
          // 1基础格式化
          if (res && res.acBasicsResp) {
            this.acBasicsReq = Object.assign(this.acBasicsReq, res.acBasicsResp)
          }
          if (res.acBasicsResp.startDate && res.acBasicsResp.endDate) {
            this.acBasicsReq.activityTime = [res.acBasicsResp.startDate, res.acBasicsResp.endDate]
          } else {
            this.acBasicsReq.activityTime = []
          }
          if (res.acBasicsResp.cover) {
            this.acBasicsReq.accessoryBOList1 = [
              {
                accessoryName: '',
                accessoryUrl: res.acBasicsResp.cover,
                name: '',
                url: res.acBasicsResp.cover
              }
            ]
          } else {
            this.acBasicsReq.accessoryBOList1 = []
          }
          if (res.acBasicsResp.topStyle) {
            this.acBasicsReq.accessoryBOList2 = [
              {
                accessoryName: '',
                accessoryUrl: res.acBasicsResp.topStyle,
                name: '',
                url: res.acBasicsResp.topStyle
              }
            ]
          } else {
            this.acBasicsReq.accessoryBOList2 = []
          }
          if (res.acBasicsResp.onlineSalesOffice) {
            this.acBasicsReq.accessoryBOList3 = [
              {
                accessoryName: '',
                accessoryUrl: res.acBasicsResp.onlineSalesOffice,
                name: '',
                url: res.acBasicsResp.onlineSalesOffice
              }
            ]
          } else {
            this.acBasicsReq.accessoryBOList3 = []
          }

          if (res.acBasicsResp.projectShow) {
            this.acBasicsReq.accessoryBOList4 = []
            let porSh = res.acBasicsResp.projectShow.split(',')
            porSh.forEach((item) => {
              this.acBasicsReq.accessoryBOList4.push({
                accessoryName: '',
                accessoryUrl: item,
                name: '',
                url: item
              })
            })
          } else {
            this.acBasicsReq.accessoryBOList4 = []
          }
          // 2奖品格式化
          this.acPrizeReqList = []

          if (res && res.acPrizeRespList) {
            res.acPrizeRespList.forEach((item) => {
              item.type = String(item.type)
              if (item.showLocation) {
                item.showLocation = item.showLocation.split(',')
              } else {
                item.showLocation = []
              }
              if (item.cover) {
                item.accessoryBOList5 = [
                  {
                    accessoryName: '',
                    accessoryUrl: item.cover,
                    name: '',
                    url: item.cover
                  }
                ]
              } else {
                item.accessoryBOList5 = []
              }

              this.acPrizeReqList.push(item)
            })
          }

          // 3抽奖格式化
          if (res && res.acLotteryResp) {
            this.acLotteryReq = res.acLotteryResp

            this.acLotteryReq.winningLimit = res.acLotteryResp.winningLimit ? '1' : '0'
            this.acLotteryReq.everydayWinning = res.acLotteryResp.everydayWinning ? '1' : '0'
          }
          // tab4参与条件
          if (res && res.acParticipationTaskRespList.length) {
            this.acParticipationTaskReqList.conditions = []
            res.acParticipationTaskRespList.forEach((item) => {
              // 手机号
              if (item.type == 1) {
                this.acParticipationTaskReqList.phoneAuthorization = item.isOpen
                // 范围
              } else if (item.type == 2) {
                this.acParticipationTaskReqList.locationLimitation = item.isOpen
                if (item.isOpen) {
                  this.conditionsFlag = true
                } else {
                  this.conditionsFlag = false
                }

                // let _index = item.areaList && item.areaList.findIndex(areaChild => {
                //   return areaChild.cityName == '市辖区'
                // })
                // if (_index != '-1') {
                //   item.areaList && item.areaList.splice(_index, 1)
                // }

                // item.areaList = item.areaList && item.areaList.filter((areaChild) => {
                //   return areaChild.cityName.indexOf('周边') == '-1'
                // })
                item.areaList =
                  item.areaList &&
                  item.areaList.filter((areaChild) => {
                    return (
                      areaChild.cityName.indexOf('周边') == '-1' &&
                      areaChild.cityName != '市辖区' &&
                      areaChild.cityName != '郑州高新技术产业开发区' &&
                      areaChild.cityName != '高新园区' &&
                      areaChild.cityName != '高新区'
                    )
                  })

                item.cityList =
                  item.cityList &&
                  item.cityList.filter((cityChild) => {
                    return (
                      cityChild.cityName != '省直辖县级行政区划' &&
                      cityChild.cityName != '自治区直辖县级行政区划' &&
                      cityChild.cityName != '县'
                    )
                  })

                this.acParticipationTaskReqList.conditions.push({
                  locationOptions: String(item.locationOptions),
                  provinceCode: String(item.provinceId),
                  provinceName: item.province,
                  cityName: item.city,
                  cityCode: String(item.cityId),
                  areaCode: String(item.areaId),
                  areaName: item.area,
                  // streetCode = item.plateId,
                  // streetName = item.plate,
                  signAddress: item.signAddress,
                  latitude: item.latitude,
                  longitude: item.longitude,
                  scope: item.scope === null ? '' : String(item.scope),
                  cityList: item.cityList,
                  areaList: item.areaList
                })
              }
            })
            console.log(
              this.acParticipationTaskReqList,
              'this.acParticipationTaskReqListthis.acParticipationTaskReqListthis.acParticipationTaskReqList'
            )
          }
          // 5助力条件
          if (res && res.acHelpTaskRespList.length) {
            res.acHelpTaskRespList.forEach((item) => {
              // 视频
              if (item.type == 1) {
                this.assist.videoHelpId = item.helpId
                this.assist.seeFlag = item.isHelp
                this.assist.videoId = item.videoCode
                this.assist.contentId = item.videoContentCode
                this.assist.seeDuration = item.videoViewDuration
                this.assist.getRaffleNum = item.shareCount
              } else {
                this.assist.shareHelpId = item.helpId
                this.assist.shareFlag = item.isHelp
                this.assist.shareNum = item.shareCount
              }
            })
          }
          this.options = editMgr.options(this)
          this.$refs.info1.init(this.options, this.acBasicsReq)

          this.options2 = editMgr.options2(this)
          this.options3 = editMgr.options3(this)
          this.$refs.info3.init(this.options3, this.acLotteryReq)
          this.options4 = editMgr.options4(this)
          this.$refs.info4.init(this.options4, this.acParticipationTaskReqList)

          this.options41 = editMgr.options41(this)
          // this.$refs.info41.init(this.options41, this.acParticipationTaskReqList
          //   .conditions)

          this.options5 = editMgr.options5(this)
          this.$refs.info5.init(this.options5, this.assist)
          this.locationFn()
        })
        this.imgFlag = true
      },
      dataProcess() {
        // 基础数据处理
        this.acBasicsReq.acId = this.acId

        this.acBasicsReq.promoteSn = this.promoteSn
        ;(this.acBasicsReq.housesId = this.$dt.buildInfo().housesId),
          (this.acBasicsReq.cover = this.acBasicsReq.accessoryBOList1[0]
            ? this.acBasicsReq.accessoryBOList1[0].accessoryUrl
            : '')
        this.acBasicsReq.topStyle = this.acBasicsReq.accessoryBOList2[0]
          ? this.acBasicsReq.accessoryBOList2[0].accessoryUrl
          : ''
        this.acBasicsReq.onlineSalesOffice = this.acBasicsReq.accessoryBOList3[0]
          ? this.acBasicsReq.accessoryBOList3[0].accessoryUrl
          : ''
        let projectShow = []
        if (this.acBasicsReq.accessoryBOList4 && this.acBasicsReq.accessoryBOList4.length > 0) {
          this.acBasicsReq.accessoryBOList4.forEach((item) => {
            projectShow.push(item.accessoryUrl)
          })
          this.acBasicsReq.projectShow = projectShow.join(',')
        } else {
          this.acBasicsReq.projectShow = ''
        }
        this.acBasicsReq.startDate = this.acBasicsReq.activityTime[0] ? this.acBasicsReq.activityTime[0] : ''
        this.acBasicsReq.endDate = this.acBasicsReq.activityTime[1] ? this.acBasicsReq.activityTime[1] : ''
        // 奖品数据处理
        let acPrizeReqList = this.$tool.deepClone(this.acPrizeReqList)
        acPrizeReqList.forEach((item) => {
          item.cover = item.accessoryBOList5[0] ? item.accessoryBOList5[0].accessoryUrl : ''
          item.showLocation = item.showLocation.join(',')
          item.acId = this.acId
          item.housesId = this.$dt.buildInfo().housesId
        })

        // tab4参与条件
        let acParticipationTaskReqList = [
          {
            acId: this.acId,
            housesId: this.$dt.buildInfo().housesId,
            type: '1',
            isOpen: true
          }
        ]
        console.log(this.acParticipationTaskReqList, '此处处理成后台需要的格式')
        if (this.acParticipationTaskReqList.locationLimitation) {
          this.acParticipationTaskReqList.conditions.forEach((item) => {
            // 限定范围
            if (item.locationOptions == '1') {
              let scopeV = {
                acId: this.acId,
                housesId: this.$dt.buildInfo().housesId,
                isOpen: true,
                type: '2',
                scope: String(item.scope),
                locationOptions: item.locationOptions,
                signAddress: item.signAddress,
                latitude: item.latitude,
                longitude: item.longitude
              }
              acParticipationTaskReqList.push(scopeV)
              // 限定地区
            } else if (item.locationOptions == '2') {
              let scopeV = {
                acId: this.acId,
                housesId: this.$dt.buildInfo().housesId,
                isOpen: true,
                type: '2',
                locationOptions: item.locationOptions,
                province: item.provinceName,
                provinceId: item.provinceCode,
                city: item.cityName,
                cityId: item.cityCode,
                // plate: item.streetName,
                // plateId: item.streetCode,
                area: item.areaName,
                areaId: item.areaCode
                // cityList: item.cityList,
                // areaList: item.areaList
              }
              acParticipationTaskReqList.push(scopeV)
            }
          })
        } else {
          let scopeV = {
            acId: this.acId,
            housesId: this.$dt.buildInfo().housesId,
            isOpen: false,
            type: '2'
          }
          acParticipationTaskReqList.push(scopeV)
        }
        // 助力条件处理
        let acHelpTaskReqList = []
        if (this.assist.seeFlag) {
          let objAssist = {
            acId: this.acId,
            housesId: this.$dt.buildInfo().housesId,
            isHelp: true,
            type: '1',
            shareCount: this.assist.getRaffleNum,
            videoCode: this.assist.videoId,
            videoContentCode: this.assist.contentId,
            videoViewDuration: this.assist.seeDuration,
            helpId: this.assist.videoHelpId
          }
          acHelpTaskReqList.push(objAssist)
        } else {
          let objAssist = {
            acId: this.acId,
            housesId: this.$dt.buildInfo().housesId,
            helpId: this.assist.videoHelpId,
            isHelp: false,
            type: '1'
          }
          acHelpTaskReqList.push(objAssist)
        }
        if (this.assist.shareFlag) {
          let objAssist = {
            acId: this.acId,
            housesId: this.$dt.buildInfo().housesId,
            helpId: this.assist.shareHelpId,
            isHelp: true,
            type: '2',
            shareCount: this.assist.shareNum
          }
          acHelpTaskReqList.push(objAssist)
        } else {
          let objAssist = {
            acId: this.acId,
            housesId: this.$dt.buildInfo().housesId,
            helpId: this.assist.shareHelpId,
            isHelp: false,
            type: '2'
          }
          acHelpTaskReqList.push(objAssist)
        }

        let acLotteryReq = Object.assign({}, this.acLotteryReq)
        if (acLotteryReq.winningLimit === '0') {
          acLotteryReq.winningLimit = false
        } else {
          acLotteryReq.winningLimit = true
        }

        if (acLotteryReq.everydayWinning === '0') {
          acLotteryReq.everydayWinning = false
        } else {
          acLotteryReq.everydayWinning = true
        }

        acLotteryReq.acId = this.acIdonClickTabBox
        acLotteryReq.housesId = this.$dt.buildInfo().housesId
        return new Promise((resolve, reject) => {
          let params = {
            acBasicsReq: this.acBasicsReq, //基础带活动id
            acPrizeReqList: acPrizeReqList,
            acLotteryReq: acLotteryReq,
            acParticipationTaskReqList: acParticipationTaskReqList,
            acHelpTaskReqList: acHelpTaskReqList
          }

          if (this.acBasicsReq.topStyle) {
            let img = document.getElementById('scream') //图片节点
            let c = document.getElementById('myCanvas') //canvas元素
            this.$dt.tool.getUrlBase64(this.acBasicsReq.topStyle).then((res) => {
              if (res) {
                this.base64Image = res
                setTimeout(() => {
                  this.$dt.tool.rgbafun(img, c).then((res) => {
                    params.acBasicsReq.backgroundColor = res
                    resolve(params)
                  })
                }, 0)
              }
            })
          } else {
            params.acBasicsReq.backgroundColor = null
            resolve(params)
          }
        })
      },
      onGetIdx(idx) {
        this.num = idx
        if (this.num == '0') {
          this.iframeUrl = `${this.$dt.env.h5Url}/market/#/pages_com/lottery/index?acId=${this.acId}`
        } else {
          this.iframeUrl = `${this.$dt.env.h5Url}/market/#/pages_com/lottery/detail?acId=${this.acId}&times=${this.acLotteryReq.initialLotteryCount}`
        }
      },
      helpClick() {
        this.$refs.helpModel.show()
      },
      closeCurrent() {
        this.$Modal.confirm({
          title: '关闭',
          content: '<p>如有修改未保存数据将丢失，是否离开当前页面？</p>',
          onOk: () => {
            this.$router.push({
              path: '/marketingCenter/activityManagement/activity'
            })
          }
        })
      },

      check1() {
        return this.$refs.info1.validate().then((res) => {
          if (res) {
            return true
          } else {
            this.tabsBox = '1'
            return false
          }
        })
      },
      check3() {
        return this.$refs.info3.validate().then((res) => {
          if (res) {
            return true
          } else {
            this.tabsBox = '3'
            return false
          }
        })
      },
      check4() {
        if (this.conditionsFlag) {
          return this.$refs.formValidate.validate((res) => {
            if (res) {
              return true
            } else {
              this.tabsBox = '4'
              return false
            }
          })
        } else {
          return true
        }
      },

      check5() {
        return this.$refs.info5.validate().then((res) => {
          if (res) {
            return true
          } else {
            this.tabsBox = '5'
            return false
          }
        })
      },
      check2() {
        let countFlag = this.acPrizeReqList.some((item) => {
          return item.count > 0
        })

        if (!countFlag) {
          this.$Message.warning('至少有一个奖品的数量不为0')
          this.tabsBox = '2'
          return false
        } else {
          let arr = []
          this.$refs.info2.forEach((item, index) => {
            arr.push(item.validate())
          })
          return Promise.all(arr).then((res) => {
            if (res && res.length) {
              let _index = res.findIndex((item) => {
                return item === false
              })
              if (_index == -1) {
                return true
              } else {
                this.tabsBox = '2'
                this.tabsChoose = String(_index)
                setTimeout(() => {
                  this.$refs.info2[_index].validate().then((res) => {
                    if (res) {
                    } else {
                    }
                  })
                }, 1000)
                return false
              }
            }
          })
        }
      },
      async saveCurrent(rel) {
        ;(await this.check1()) &&
          (await this.check2()) &&
          (await this.check3()) &&
          (await this.check4()) &&
          (await this.check5()) &&
          (await this.updateActivity(rel))
      },

      updateActivity(rel) {
        this.imgFlag = false
        this.dataProcess().then((res) => {
          activityMgr.updateBasics(res).then((res) => {
            if (rel === 'rel') {
              let dataVal = {
                acId: this.acId,
                status: this.acBasicsReq.status,
                times: this.acLotteryReq.initialLotteryCount,
                promoteSn: this.promoteSn
              }
              this.$refs.releaseModel.show(dataVal)
              this.getDetails()
            } else {
              this.$Message.success('保存成功')
              this.getDetails()
            }
          })
        })
      },

      releaseCurrent() {
        this.saveCurrent('rel')
      },
      onClickTab(val) {
        this.tabsChoose = String(val)
        this.options2 = editMgr.options2(this)
        this.locationFn()
      },
      mapInfo(val, index) {
        this.$set(this.acParticipationTaskReqList.conditions[index], 'scope', String(val.range))
        this.$set(this.acParticipationTaskReqList.conditions[index], 'signAddress', val.signAddress)
        this.acParticipationTaskReqList.conditions[index].latitude = val.latitude
        this.acParticipationTaskReqList.conditions[index].longitude = val.longitude
      },
      mapClick(item, index) {
        this.$refs.mapRange.show(item, index)
      },
      upRemove(item, index) {
        if (
          this.acParticipationTaskReqList.conditions &&
          this.acParticipationTaskReqList.conditions.length < 2
        ) {
        } else {
          this.acParticipationTaskReqList.conditions.splice(index, 1)
        }
      },
      upAdd() {
        if (
          this.acParticipationTaskReqList.conditions &&
          this.acParticipationTaskReqList.conditions.length > 4
        ) {
          this.$Message.warning('最多可设置5条')
        } else {
          this.acParticipationTaskReqList.conditions.push({
            locationOptions: '1', //限定范围和城市
            scope: '', //设置的范围数字
            signAddress: '', // 四级联动设置的地点
            provinceCode: '', //省
            provinceName: '',
            cityCode: '',
            cityName: '',
            cityId: '',
            areaCode: '', //区
            areaName: '',
            streetCode: '', //街道
            streetName: '',

            cityList: null
          })
        }
      },
      upAddShow(val) {
        if (val) {
          this.conditionsFlag = true
          this.acParticipationTaskReqList.conditions = [
            {
              locationOptions: '1', //限定范围和城市
              scope: '', //设置的范围数字
              signAddress: '', // 四级联动设置的地点
              provinceCode: '', //省
              provinceName: '',
              cityCode: '',
              cityName: '',
              cityId: '',
              areaCode: '', //区
              areaName: '',
              streetCode: '', //街道
              streetName: '',

              cityList: null
            }
          ]
        } else {
          this.conditionsFlag = false
          this.acParticipationTaskReqList.conditions = []
        }
      },
      addPrize() {
        if (this.acPrizeReqList && this.acPrizeReqList.length < 7) {
          this.acPrizeReqList.push({
            name: '',
            type: '1',
            accessoryBOList5: [],
            cover: '',
            count: null,
            exchangeReason: '',
            showLocation: []
          })
          this.tabsChoose = this.acPrizeReqList && String(this.acPrizeReqList.length - 1)
          this.options2 = editMgr.options2(this)
          this.locationFn()
        } else {
          this.$Message.warning('最多添加7个奖品。')
        }
      },
      removePrize() {
        if (this.acPrizeReqList && this.acPrizeReqList.length < 2) {
          this.$Message.warning('至少保留一个奖品。')
        } else {
          this.$Modal.confirm({
            title: '删除',
            content: '你确认删除该奖品？',
            closable: true,
            onOk: () => {
              this.acPrizeReqList.splice(this.tabsChoose, 1)
              this.tabsChoose = '0'
              this.locationFn()
            }
          })
        }
      },
      locationFn() {
        this.prizeLocationAll = []
        this.acPrizeReqList.forEach((item) => {
          if (item.showLocation && item.showLocation.length) {
            this.prizeLocationAll.push(...item.showLocation)
          }
        })
        if (this.prizeLocationAll.length < 7) {
          this.optLocation.forEach((item) => {
            if (this.prizeLocationAll.indexOf(item.key) != '-1' || item.key == '9') {
              if (this.acPrizeReqList[this.tabsChoose].showLocation.indexOf(item.key) != '-1') {
                item.disabled = false
              } else {
                item.disabled = true
              }
            } else {
              item.disabled = false
            }
          })
        } else {
          this.optLocation.forEach((item) => {
            if (this.prizeLocationAll.indexOf(item.key) != '-1' || item.key == '9') {
              if (this.acPrizeReqList[this.tabsChoose].showLocation.indexOf(item.key) != '-1') {
                item.disabled = false
              } else {
                item.disabled = true
              }
            } else {
              item.disabled = true
            }
          })
        }
      }
    },
    created() {
      this.getProvinceList()
      this.iframeUrl = `${this.$dt.env.h5Url}/market/#/pages_com/lottery/index?acId=${this.acId}`
    },
    mounted() {
      this.getDetails()
      this.onGetIdx('0')
    }
  }
</script>
<style lang="scss" scoped>
  .addEditActivity {
    height: 100vh;
    .acrivityTitle {
      background-color: #f5f5f5;
      box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
      padding: 0 14px 10px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
    }
    .setBoth {
      width: 100%;
      display: flex;
      flex-direction: row;
      .bothLeft {
        width: 400px;
        padding-left: 20px;
        .viewClass {
          padding: 10px 0 0 10px;
        }
        .yeTit {
          display: flex;
          flex-direction: row;
          width: 200px;

          span {
            cursor: pointer;
            padding: 5px 10px 10px 10px;
            line-height: 2;
          }

          span.active {
            color: #2d8cf0;
          }
        }

        .yeCon {
          width: 375px;
          height: 667px;
          .yeCOnTel {
            display: block;
            width: 100%;
            position: relative;

            span {
              position: absolute;
              top: 432px;
              left: 122px;
              color: #000;
            }
          }

          img {
            display: block;
            width: 100%;
          }
        }
      }

      .setAll {
        flex: 1;
        width: 100%;
        max-width: 800px;
        padding-left: 20px;
        padding-top: 20px;
        box-sizing: border-box;

        .sp1 {
          position: absolute;
          top: 3px;
          left: 52px;
          cursor: pointer;
          z-index: 1029;
        }

        color: rgba(89, 111, 164, 1);
      }
    }

    .conditionsCon {
      display: flex;
      flex-direction: row;
      justify-content: space-between;

      .conditionsAddress {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
      }

      .conditionscity {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        width: 480px;

        > * {
          width: 100%;
        }
      }
    }
  }
</style>
